<script setup lang="ts">
import { reactive, computed, provide, shallowRef, onMounted, ref, nextTick } from 'vue';
import { showSuccessToast, showDialog, showToast } from 'vant';
import { is_ios } from '@/utils/util';
import { geturlparam } from '@/utils/util';
import formPricker from '@/components/formPricker.vue';
import formDatePricker from '@/components/formDatePricker.vue';
import formAreaPricker from '@/components/formAreaPricker.vue';
import { useGetAreaJson } from '@/composables/getAreaJson';
import { useBankList } from './hooks/getHfBankList';
import { useLargenScreen } from '@/composables/useLargenScreen';
import { useRouter } from 'vue-router';
import headerNavBar from '@/components/headerNavBar.vue';
import { UserApply, UserApplyBank, CompanyApply, CompanyApplyBank, myAccountDetail } from '@/common/api/bankCard';
import { useUserInfo } from '@/stores/userInfo';
import { useToastLoading } from '@/composables/useToastLoading';

const router = useRouter();
const userInfo = useUserInfo();

// 获取url地址参数
const urlParam = geturlparam();
const uid = computed(() => userInfo.state.uid);
const BASE_KEY = 'userInfoOpenAccount_register_json';
const REGISTER_KEY = BASE_KEY + '_' + uid.value;
// 校验正则
const certNoPattern =
  /^(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|71|8[1-2])\d{4}(19\d{2}|20[0-2]\d)(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}([0-9Xx])$/; // 身份证正则校验

// 只读状态
const readOnly = ref(false);
provide('readOnly', readOnly);

// 监听浏览器窗口变化
const [largenScreen] = useLargenScreen();

// 定义引用
const cardTypeRef = shallowRef<InstanceType<typeof formPricker>>();
const certEndDateRef = shallowRef<InstanceType<typeof formDatePricker>>();
const licenseEndDate = shallowRef<InstanceType<typeof formDatePricker>>();
const legalCertEndDateRef = shallowRef<InstanceType<typeof formDatePricker>>();
const cardCertEndDateRef = shallowRef<InstanceType<typeof formDatePricker>>();

// 获取省市区json数据
const [areaPrickerOptions, regAreaPrickerOptions] = useGetAreaJson();

// 银行列表
const { bankList } = useBankList();

const form = reactive({
  register_type: '1', // 进件类型 1：个人进件 2：企业进件
  // 个人对象
  user_param: {
    name: '', // 个人姓名
    cert_no: '', // 证件号码
    cert_validity_type: '', // 1:长期有效 0:非长期有效
    cert_begin_date: '', // 个人证件有效期开始日期 示例值：20110112
    cert_end_date: '', // 个人证件有效期截止日期 示例值：20310112
    mobile_no: urlParam.get('mobile') || '', // 手机号 示例值：18611111111
  },
  // 企业对象
  enterprise_param: {
    reg_name: '', // 企业注册名称
    license_code: '', // 企业营业执照号码
    license_validity_type: '', // 证照有效期类型 1:长期有效 0:非长期有效
    license_begin_date: '', // 证照有效期起始日期
    license_end_date: '', // 证照有效期结束日期 日期格式：yyyyMMdd; 非长期有效时必填
    reg_prov_id: '', // 注册地址(省)
    reg_area_id: '', // 注册地址(市)
    reg_district_id: '', // 注册地址(区)
    reg_detail: '', // 注册地址(详细信息)
    legal_name: '', // 法人姓名
    legal_cert_no: '', // 法人证件号码
    legal_cert_validity_type: '', // 法人证件有效期类型 1:长期有效 0:非长期有效
    legal_cert_begin_date: '', // 法人证件有效期开始日期
    legal_cert_end_date: '', // 法人证件有效期截止日期 日期格式：yyyyMMdd; 非长期有效时必填
    contact_name: '', // 联系人姓名
    contact_mobile: '', // 联系人手机号
  },
  // 结算卡信息
  card_info: {
    card_type: '1', // 卡类型 0：对公，1：对私，2：对私非法人
    name: '', // 卡户名 公司名称
    card_no: '', // 卡号 银行卡号；不支持贷记卡绑定
    prov_id: '', // 银行所在省 参见 地区编码
    area_id: '', // 参见 地区编码
    bank_code: '', // 银行号
    bank_type: '', // 银行类型
    branch_name: '', // 支行名称
    cert_no: '', // 持卡人证件号码 对私必填
    cert_validity_type: '', // 持卡人证件有效期类型 对私必填 1:长期有效 0:非长期有效
    cert_begin_date: '', // 持卡人证件有效期开始日期 对私必填
    cert_end_date: '', // 持卡人证件有效期截止日期 当cert_validity_type=0时必须填写，当cert_validity_type=1可不填
  },
});
const jsonForm = JSON.stringify(form);

const loading = ref(false);
const detailLoading = ref(false);

// 持卡人信息
const cardName = computed(() => (form.card_info.card_type === '0' ? '公司名称' : '持卡人姓名'));
// 是否隐藏持卡人用户信息
const hiddenCardUserInfo = computed(() => form.register_type === '1' && form.card_info.card_type === '1');

// 表单提交成功回调
const submitSuccess = () => {
  try {
    // 通知App关闭此页面
    if (is_ios()) {
      (window as any).webkit.messageHandlers.closePage.postMessage(null);
    } else {
      (window as any).android.closePage();
    }
  } catch {
    getHfUserApplyInfo();
  } finally {
    showSuccessToast('提交成功，请返回APP操作');
    Object.assign(form, JSON.parse(jsonForm));
    localStorage.removeItem(REGISTER_KEY);
  }
};

// 表单提交
const onSubmit = async () => {
  if (form.register_type === '1') {
    handleUserApply();
  } else if (form.register_type === '2') {
    handleCompanyApply();
  } else {
    showToast('进件类型错误');
  }
};

// 个人开户
const handleUserApply = async () => {
  loading.value = true;
  try {
    await UserApply({ ...form.user_param });
    await UserApplyBank({
      ...form.card_info,
      name: form.user_param.name,
      cert_no: form.user_param.cert_no,
      cert_validity_type: form.user_param.cert_validity_type,
      cert_begin_date: form.user_param.cert_begin_date,
      cert_end_date: form.user_param.cert_end_date,
      prov_id: form.card_info.prov_id.padEnd(6, '0'),
      area_id: form.card_info.area_id.padEnd(6, '0'),
    });
    submitSuccess();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

// 企业开户
const handleCompanyApply = async () => {
  loading.value = true;
  try {
    await CompanyApply({
      ...form.enterprise_param,
      reg_prov_id: form.enterprise_param.reg_prov_id.padEnd(6, '0'),
      reg_area_id: form.enterprise_param.reg_area_id.padEnd(6, '0'),
      reg_district_id: form.enterprise_param.reg_district_id.padEnd(6, '0'),
    });
    await CompanyApplyBank({ ...form.card_info });
    submitSuccess();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};

// 设置暂存
const setRegister = () => {
  if (uid.value) {
    localStorage.setItem(REGISTER_KEY, JSON.stringify(form));
    showSuccessToast('暂存成功');
  } else {
    showToast('获取用户ID失败');
  }
};
// 获取暂存
onMounted(() => {
  let localRegister = localStorage.getItem(REGISTER_KEY);
  // 尝试获取全局缓存
  if (!localRegister) {
    localRegister = localStorage.getItem(BASE_KEY);
  }
  // 赋初始值
  if (!localRegister) {
    localRegister = jsonForm;
  }

  if (localRegister) {
    const result = JSON.parse(localRegister);
    Object.assign(form, result);
  }
});

// 获取用户进件信息
const getHfUserApplyInfo = async () => {
  detailLoading.value = true;
  try {
    const res = await myAccountDetail({});
    if (!res.result.data.param) {
      return;
    }
    readOnly.value = true;
    window.document.title = '用户基本信息开户详情';

    const param = JSON.parse(res.result.data?.param || '{}');
    const preparam = JSON.parse(res.result.data?.preparam || '{}');
    // console.log('param: ', param);
    // console.log('preparam: ', preparam);

    // 持卡人信息
    if (param.card_info) {
      param.card_info = JSON.parse(param.card_info);
      Object.assign(form.card_info, {
        ...param.card_info,
        name: param.card_info.name || param.card_info.card_name,
        prov_id: param.card_info.prov_id.slice(0, 2),
        area_id: param.card_info.area_id.slice(0, 4),
      });
    }
    // 企业开户信息
    if (preparam.reg_name) {
      form.register_type = '2';
      Object.assign(form.enterprise_param, {
        ...preparam,
        reg_prov_id: preparam.reg_prov_id.slice(0, 2),
        reg_area_id: preparam.reg_area_id.slice(0, 4),
      });
    }
    // 个人开户信息
    if (preparam.mobile_no) {
      form.register_type = '1';
      Object.assign(form.user_param, {
        ...preparam,
      });
    }

    // 用户提示
    nextTick(() => {
      showDialog({
        message: '您的结算开户已成功！若需修改收款信息，请点击[编辑持卡人信息]进行调整。修改将于下一个工作日生效。',
        title: '温馨提示',
      });
    });
  } catch {
    /** empty */
  } finally {
    detailLoading.value = false;
  }
};
getHfUserApplyInfo();
useToastLoading(detailLoading);

// 编辑持卡人信息
const toEdit = () => {
  router.push('/userInfoOpenAccountEdit');
};
</script>
<template>
  <div class="userInfoOpenAccount" :class="{ boxShadow: largenScreen }">
    <headerNavBar />
    <van-form @submit="onSubmit" label-align="top" scroll-to-error required="auto" :readonly="readOnly">
      <form-pricker
        v-model="form.register_type"
        label="进件类型"
        name="register_type"
        :columns="[
          { text: '个人进件', value: '1' },
          { text: '企业进件', value: '2' },
        ]"
        @onConfirm="
          (value) => {
            if (value === '1') {
              form.card_info.card_type = '1';
            } else {
              form.card_info.card_type = '0';
            }
            // cardTypeRef?.setColumn('0', 'disabled', value === '1');
          }
        "
      />
      <form-pricker
        v-if="false"
        v-model="form.card_info.card_type"
        ref="cardTypeRef"
        label="结算类型"
        name="card_info_card_type"
        :columns="[
          { text: '对公', value: '0' },
          { text: '对私', value: '1' },
        ]"
      />
      <template v-if="form.register_type === '1'">
        <div class="title">个人基本信息</div>
        <van-field
          label-class="u_label"
          v-model.trim="form.user_param.name"
          name="name"
          label="个人姓名"
          placeholder="请输入个人姓名"
          :rules="[{ required: true, message: '请填写个人姓名' }]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.user_param.cert_no"
          name="cert_no"
          label="身份证"
          placeholder="请输入身份证"
          clearable
          clear-trigger="always"
          :rules="[
            { required: true, message: '请填写身份证' },
            { pattern: certNoPattern, message: '请正确输入身份证' },
          ]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.user_param.mobile_no"
          name="mobile_no"
          type="number"
          maxlength="11"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '请填写手机号' }]"
        />
        <form-pricker
          v-model="form.user_param.cert_validity_type"
          label="个人证件有效类型"
          name="cert_validity_type"
          :columns="[
            { text: '非长期有效', value: '0' },
            { text: '长期有效', value: '1' },
          ]"
        />
        <formDatePricker
          v-model="form.user_param.cert_begin_date"
          label="个人证件有效期开始日期"
          name="cert_begin_date"
          @onConfirm="
            (value) => {
              certEndDateRef?.setValue(value);
            }
          "
        />
        <template v-if="form.user_param.cert_validity_type == '0'">
          <formDatePricker
            ref="certEndDateRef"
            v-model="form.user_param.cert_end_date"
            label="个人证件有效期截止日期"
            name="cert_end_date"
          />
        </template>
      </template>
      <template v-else-if="form.register_type === '2'">
        <div class="title">企业基本信息</div>
        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.reg_name"
          name="name"
          label="企业注册名称"
          placeholder="请输入企业注册名称"
          :rules="[{ required: true, message: '请填写企业注册名称' }]"
        />
        <van-field
          label-class="u_label"
          v-model="form.enterprise_param.license_code"
          name="card_no"
          label="企业营业执照号码"
          clearable
          clear-trigger="always"
          placeholder="请输入企业营业执照号码"
          :rules="[{ required: true, message: '请填写企业营业执照号码' }]"
        />
        <form-pricker
          v-model="form.enterprise_param.license_validity_type"
          label="证照有效期类型"
          name="license_validity_type"
          :columns="[
            { text: '非长期有效', value: '0' },
            { text: '长期有效', value: '1' },
          ]"
        />
        <formDatePricker
          v-model="form.enterprise_param.license_begin_date"
          label="证照有效期起始日期"
          name="license_begin_date"
          @onConfirm="
            (value) => {
              licenseEndDate?.setValue(value);
            }
          "
        />
        <template v-if="form.enterprise_param.license_validity_type == '0'">
          <formDatePricker
            ref="licenseEndDate"
            v-model="form.enterprise_param.license_end_date"
            label="证照有效期结束日期"
            name="license_end_date"
          />
        </template>
        <formAreaPricker
          :model-value="[
            form.enterprise_param.reg_prov_id,
            form.enterprise_param.reg_area_id,
            form.enterprise_param.reg_district_id,
          ]"
          label="注册地址"
          name="reg_area"
          :columns="regAreaPrickerOptions"
          @on-confirm="
            (value) => {
              form.enterprise_param.reg_prov_id = value[0].value;
              form.enterprise_param.reg_area_id = value[1].value;
              form.enterprise_param.reg_district_id = value[2].value;
            }
          "
        />

        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.reg_detail"
          name="reg_detail"
          label="注册地址(详细信息)"
          placeholder="请输入注册地址(详细信息)"
          :rules="[{ required: true, message: '请填写注册地址(详细信息)' }]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.legal_name"
          name="legal_name"
          label="法人姓名"
          placeholder="请输入法人姓名"
          :rules="[{ required: true, message: '请填写法人姓名' }]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.legal_cert_no"
          name="legal_cert_no"
          label="法人证件号码"
          placeholder="请输入法人证件号码"
          clearable
          clear-trigger="always"
          :rules="[
            { required: true, message: '请填写法人证件号码' },
            { pattern: certNoPattern, message: '请正确输入法人证件号码' },
          ]"
        />
        <form-pricker
          v-model="form.enterprise_param.legal_cert_validity_type"
          label="法人证件有效期类型"
          name="legal_cert_validity_type"
          :columns="[
            { text: '非长期有效', value: '0' },
            { text: '长期有效', value: '1' },
          ]"
        />
        <formDatePricker
          v-model="form.enterprise_param.legal_cert_begin_date"
          label="法人证件有效期开始日期"
          name="legal_cert_begin_date"
          @onConfirm="
            (value) => {
              legalCertEndDateRef?.setValue(value);
            }
          "
        />
        <template v-if="form.enterprise_param.legal_cert_validity_type == '0'">
          <formDatePricker
            ref="legalCertEndDateRef"
            v-model="form.enterprise_param.legal_cert_end_date"
            label="法人证件有效期截止日期"
            name="legal_cert_end_date"
          />
        </template>
        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.contact_name"
          name="contact_name"
          label="联系人姓名"
          placeholder="请输入联系人姓名"
          :rules="[{ required: true, message: '请填写联系人姓名' }]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.enterprise_param.contact_mobile"
          name="contact_mobile"
          type="number"
          maxlength="11"
          label="联系人手机号"
          placeholder="请输入联系人手机号"
          :rules="[{ required: true, message: '请填写联系人手机号' }]"
        />
      </template>

      <div class="title">持卡人信息</div>
      <van-field
        v-if="!hiddenCardUserInfo"
        label-class="u_label"
        v-model.trim="form.card_info.name"
        name="name"
        :label="cardName"
        :placeholder="`请输入${cardName}`"
        :rules="[{ required: true, message: `请填写${cardName}` }]"
      />
      <template v-if="form.card_info.card_type == '1' && !readOnly">
        <form-pricker v-model="form.card_info.bank_type" label="银行类型" name="card_bank_type" :columns="bankList" />
      </template>

      <van-field
        label-class="u_label"
        v-model="form.card_info.card_no"
        name="card_no"
        type="number"
        label="银行卡号"
        clearable
        clear-trigger="always"
        placeholder="请输入银行卡号"
        :rules="[
          { required: true, message: '请填写银行卡号' },
          { pattern: /\d/, message: '请正确输入银行卡号' },
        ]"
      />
      <formAreaPricker
        :model-value="[form.card_info.prov_id, form.card_info.area_id]"
        label="银行所在省/市"
        name="area"
        :columns="areaPrickerOptions"
        @on-confirm="
          (value) => {
            form.card_info.prov_id = value[0].value;
            form.card_info.area_id = value[1].value;
          }
        "
      />
      <template v-if="form.card_info.card_type == '0'">
        <form-pricker
          v-model="form.card_info.bank_code"
          label="银行号"
          name="card_bank_code"
          :columns="[
            { text: '中国银行	', value: '01040000' },
            { text: '中国农业银行', value: '01030000' },
            { text: '中国工商银行', value: '01020000' },
            { text: '中国建设银行', value: '01050000' },
            { text: '交通银行', value: '03010000' },
            { text: '中国邮政储蓄银行', value: '04030000' },
            { text: '华夏银行', value: '03040000' },
            { text: '招商银行', value: '03080000' },
            { text: '上海浦东发展银行', value: '03100000' },
            { text: '浙商银行', value: '03160000' },
            { text: '广发银行', value: '03060000' },
            { text: '天津银行', value: '03130012' },
            { text: '济宁银行', value: '31346100' },
            { text: '中国民生银行', value: '03050000' },
          ]"
        />
        <van-field
          label-class="u_label"
          v-model.trim="form.card_info.branch_name"
          name="branch_name"
          label="支行名称"
          placeholder="请输入支行名称"
          :rules="[{ required: true, message: '请填写支行名称' }]"
        />
      </template>
      <template v-else-if="form.card_info.card_type == '1' && !hiddenCardUserInfo">
        <van-field
          label-class="u_label"
          v-model.trim="form.card_info.cert_no"
          name="cert_no"
          label="持卡人证件号码"
          placeholder="请输入持卡人证件号码"
          clearable
          clear-trigger="always"
          :rules="[
            { required: true, message: '请填写持卡人证件号码' },
            { pattern: certNoPattern, message: '请正确输入持卡人证件号码' },
          ]"
        />
        <form-pricker
          v-model="form.card_info.cert_validity_type"
          label="持卡人证件有效期类型"
          name="card_cert_validity_type"
          :columns="[
            { text: '非长期有效', value: '0' },
            { text: '长期有效', value: '1' },
          ]"
        />
        <formDatePricker
          v-model="form.card_info.cert_begin_date"
          label="持卡人证件有效期开始日期"
          name="legal_cert_begin_date"
          @onConfirm="
            (value) => {
              cardCertEndDateRef?.setValue(value);
            }
          "
        />
        <template v-if="form.card_info.cert_validity_type == '0'">
          <formDatePricker
            ref="cardCertEndDateRef"
            v-model="form.card_info.cert_end_date"
            label="持卡人证件有效期截止日期"
            name="card_cert_end_date"
          />
        </template>
      </template>

      <div class="submitBox">
        <template v-if="!readOnly">
          <van-button
            round
            block
            type="primary"
            :disabled="detailLoading"
            class="mr-10"
            color="#EC2D69"
            native-type="submit"
            :loading="loading"
          >
            提交
          </van-button>
          <van-button round block @click="setRegister" :disabled="detailLoading"> 暂存 </van-button>
        </template>
        <template v-else>
          <van-button round block type="primary" color="#EC2D69" @click="toEdit"> 编辑持卡人信息 </van-button>
        </template>
        <!-- 底部安全区 -->
        <div class="van-safe-area-bottom"></div>
      </div>
      <!-- 底部安全区 -->
      <div class="van-safe-area-bottom"></div>
    </van-form>
  </div>
</template>
<style lang="less" scoped>
.userInfoOpenAccount {
  max-width: 400px;
  margin: 0 auto;
  padding-bottom: 70px;

  .title {
    font-size: 12px;
    color: #8a8a8a;
    margin: 15px 15px 7.5px;
  }
  :deep(.u_label) {
    color: #7a7a7a;
  }
  .mr-10 {
    margin-right: 10px;
  }
  .submitBox {
    width: 100%;
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    padding: 16px;
    display: flex;
  }
}
.userInfoOpenAccount.boxShadow {
  margin: 3vh auto;
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
}
</style>
../../composables/getAreaJson
